<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24" style="height: 100vh">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="用户名称" prop="username">
            <el-input
              v-model="queryParams.username"
              placeholder="请输入用户名称"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              >新增</el-button
            >
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="tableList" height="70%">
          <el-table-column
            label="用户名称"
            align="center"
            key="username"
            prop="username"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="部门"
            align="center"
            key="deptName"
            prop="deptName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="手机号码"
            align="center"
            key="phone"
            prop="phone"
            width="120"
          />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{ dateFormat(new Date(scope.row.createTime)) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="200"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                v-if="scope.row.userId !== 1"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-key"
                @click="handleResetPwd(scope.row)"
                >重置</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-upload2"
                @click="handlePermit(scope.row)"
                >上传权限</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                @click="handlePermitDetail(scope.row)"
                >查看权限</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.current"
          :limit.sync="queryParams.size"
          @pagination="getList"
        />
        <!-- 上传 -->
        <el-upload
          v-show="false"
          ref="upload"
          class="upload-demo"
          action="/api/shipping/seamap/import"
          :file-list="fileList"
          :show-file-list="false"
          accept=".txt"
          :before-upload="beforeUpload"
        >
        </el-upload>
      </el-col>
    </el-row>

    <form-dialog
      ref="form"
      @submit_success="getList"
      :deptOptions="deptOptions"
    ></form-dialog>
    <permit-dialog ref="permit"></permit-dialog>
  </div>
</template>

<script>
import { getPage, remove, edit, uploadPermit } from "@/api/sys/user";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { rules, initSearchForm, getDeptName } from "./options";
import sysMixins from "@/mixins/sysMixins";
import { getDeptTree } from "@/api/sys/dept";
import { dateFormat } from "@/utils/date";
import FormDialog from "./form";
import PermitDialog from "./permitDialog";

export default {
  name: "User",
  mixins: [sysMixins],
  components: { FormDialog, PermitDialog },
  data() {
    return {
      queryParams: initSearchForm(),
      rules,
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 角色选项
      roleOptions: [],
      defaultProps: {
        children: "children",
        label: "deptName",
      },
      dateFormat,
      fileList: [],
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getDeptTree();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      getPage(this.queryParams).then(({ data }) => {
        data.records = data.records.map((m) => {
          m.deptName = getDeptName(m.deptId, this.deptOptions);
          return m;
        });
        this.tableList = data.records;
        this.total = data.total;
        this.loading = false;
      });
    },
    getDeptTree() {
      getDeptTree().then(({ data }) => {
        this.deptOptions = data;
        this.getList();
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      // this.resetForm("queryForm");
      this.queryParams = initSearchForm();
      this.handleQuery();
    },
    handleAdd() {
      this.$refs.form.open("add");
    },
    handleUpdate(row) {
      if (typeof row.roleIds === "string") row.roleIds = row.roleIds.split(",");
      this.$refs.form.open("edit", row);
    },
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.username + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          row.password = value;
          edit(row).then(() => {
            this.$message.success("修改成功，新密码是：" + value);
          });
        })
        .catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.selectIds;
      this.$confirm(
        '是否确认删除用户名为"' + row.username + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function() {
          return remove(userIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    // 上传海图权限
    handlePermit(row) {
      this.uploadData = { ...row };
      this.$refs.upload.$children[0].$refs.input.click();
    },
    beforeUpload(file) {
      let fd = new FormData();
      fd.append("file", file, "fileName");
      uploadPermit(fd, { userId: this.uploadData.userId }).then(() => {
        this.$message.success("上传成功！");
        this.getList();
        // 刷新用户信息 - 重新获取userKey
        this.$store
          .dispatch("GetInfo")
          .then(() => {})
          .catch(() => {});
      });
      return false;
    },
    handlePermitDetail(row) {
      this.$refs.permit.open(row);
    },
  },
};
</script>
<style scoped></style>
